#include "D3DUtil.h"
#include "D3DInput.h"
#include "D3DApp.h"

D3DInput* gInput = 0;

D3DInput::D3DInput(DWORD keyboardCoopFlags, DWORD mouseCoopFlags){

	ZeroMemory(mKeyboardState, sizeof(mKeyboardState));
	ZeroMemory(&mMouseState, sizeof(mMouseState));

	HR(DirectInput8Create(gApp->getAppInst(), DIRECTINPUT_VERSION, 
		IID_IDirectInput8, (void**)&mInput, 0));

	HR(mInput->CreateDevice(GUID_SysKeyboard, &mKeyboard, 0));
	HR(mKeyboard->SetDataFormat(&c_dfDIKeyboard));
	HR(mKeyboard->SetCooperativeLevel(gApp->getMainWnd(), keyboardCoopFlags));
	HR(mKeyboard->Acquire());

	HR(mInput->CreateDevice(GUID_SysMouse, &mMouse, 0));
	HR(mMouse->SetDataFormat(&c_dfDIMouse2));
	HR(mMouse->SetCooperativeLevel(gApp->getMainWnd(), mouseCoopFlags));
	HR(mMouse->Acquire());
}

D3DInput::~D3DInput(){
	ReleaseCOM(mInput);
	mKeyboard->Unacquire();
	mMouse->Unacquire();
	ReleaseCOM(mKeyboard);
	ReleaseCOM(mMouse);
}

void D3DInput::poll(){
	HRESULT hr = mKeyboard->GetDeviceState(sizeof(mKeyboardState), (void**)&mKeyboardState); 
	if(FAILED(hr)){
		ZeroMemory(mKeyboardState, sizeof(mKeyboardState));
		hr = mKeyboard->Acquire();
	}

	hr = mMouse->GetDeviceState(sizeof(DIMOUSESTATE2), (void**)&mMouseState); 
	if(FAILED(hr)){
		ZeroMemory(&mMouseState, sizeof(mMouseState));
		hr = mMouse->Acquire(); 
	}
}

bool D3DInput::keyDown(unsigned char key){
	return (mKeyboardState[key] & 0x80) != 0;
}

bool D3DInput::mouseDown(int button){
	return (mMouseState.rgbButtons[button] & 0x80) != 0;
}

float D3DInput::mouseDX(){
	return (float)mMouseState.lX;
}

float D3DInput::mouseDY(){
	return (float)mMouseState.lY;
}

float D3DInput::mouseDZ(){
	return (float)mMouseState.lZ;
}
